<?php
namespace app\app\model;
use think\Model;
use think\Db;
use app\app\util\PointUtils;

class PropModel extends Model{

    protected $table = "a_prop";
    public $user_id;

    /**
     * 获取道具列表
     */
    public function getList(){
        return $this->field('id,name,point,num,concat("'.config('IMG_HEAD').'",img) img')->where('status','eq',1)->select();
    }

    /**
     * 根据Id获取道具
     */
    public function getOne($id){
        return $this->where('id','eq',$id)->find();
    }

    /**
     * 兑换道具
     * @param $id
     */
    public function chargeOne($id){
        Db::query('update a_prop set num = num + 1 where id='.$id);
        $prop = $this->where('id','eq',$id)->find();
        //用户兑换+1
        Db::query('update a_user_prop set num = num + 1 where user_id ='.$this->user_id);
        Db::query('update a_users set points = points -'.$prop['point'].' where id='.$this->user_id);
        PointUtils::getUserPoint($this->user_id,-$prop['point']);
        return true;
    }

    /**
     * 使用复活卡
     */
    public function useProp(){
        $prop = Db::name('prop')->where('keyword','eq','revive')->find();
        if($prop){
            $user = Db::name('user_prop')->where('prop_id','eq',$prop['id'])->where('user_id','eq',$this->user_id)->find();
            if($user && $user['num']>=1){
                Db::query('update a_user_prop set num = num -1 where id='.$user['id']);
                $number['number'] = $user['num'] - 1;
                return $result = array('code'=>200,'msg'=>'success','data'=>$number);
            }else{
                return $result = array('code'=>402,'msg'=>'道具数量不足','data'=>'');
            }
        }else{
            return $result = array('code'=>402,'msg'=>'道具不存在','data'=>'');
        }
    }

    /**
     * 获取用户复活卡
     * @param $id
     */
    public function getUserProp($id){
        $prop = $this->where('keyword','eq','revive')->find();
        $data = Db::name('user_prop')->where('user_id','eq',$id)->where('prop_id','eq',$prop['id'])->find();
        if( empty($data) ){
            $data['num'] = 0;
        }
        return $data;
    }
}